package idv.arthur.ftp;

import java.util.Vector;

import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;

public class IsFileExist {

	public static void main(String[] args) throws JSchException {


		final JSch jsch = new JSch();
        JSch.setConfig("StrictHostKeyChecking", "no");
        Session session = null;
        ChannelSftp sftp = null;
		int res = 0;
		
        try {
        	session = jsch.getSession("Arthur", "10.144.97.99");
    		session.setPassword( "arthur7382" );
    		try {
    			session.connect();
    			sftp = (ChannelSftp) session.openChannel("sftp");
    			sftp.connect();
    			System.out.println("連線了");
    			cwdButNotmkdir(sftp,"AAAAA/SSSS");
    			
    			res = 4;
    		} catch (Exception e) {
    			System.out.println(e.getMessage());
    			e.printStackTrace();
    			if ( "Auth fail".equalsIgnoreCase(e.getMessage()) ) {
    				res=3;	//帳密不通	
    			} else if(e.getMessage().contains("Connection timed out: connect") ) {
    				res=2;	//主機不能連
    			} else if ( "No such file".equalsIgnoreCase(e.getMessage()) ) {
    				res=5;	//不存在指定路徑
    			}
    		}
    		if ( res ==4 ) {
    			try {
    				Vector<ChannelSftp.LsEntry> list = sftp.ls("*");
    				String tmp = "";
    				for(ChannelSftp.LsEntry entry : list) {
    					if ( !entry.getAttrs().isDir() ) {
    						System.out.println(entry.getFilename()+","+entry.getAttrs().getSize());	
    					}
    				}
    				
    				sftp.get("aaa.xml");	
    			} catch (Exception e) {
    				e.printStackTrace();
    				if ( "No such file".equalsIgnoreCase(e.getMessage()) ) {
    					res = 6; //檔案不存在
    				}
    			}
    		}
        } catch (Exception e) {
        	e.printStackTrace();	
        } finally {
        	if ( sftp != null ) { if ( sftp.isConnected() ) { sftp.disconnect(); } }
			if ( session != null ) { if ( session.isConnected() ) { session.disconnect(); } }
        }
        

	

	}
	public static void cwdButNotmkdir (ChannelSftp sftp, String path) throws SftpException { 
		String[] hie  = path.split("/");
		for(int i=0; i<hie.length;i++) {
			if ("".equalsIgnoreCase(hie[i])) {continue;}
			sftp.cd(hie[i]);
		}
	}
}
